package cn.cool.service.impl;

import cn.cool.entity.Article;
import cn.cool.entity.UserLikeArticleExample;
import cn.cool.mapper.ArticleMapper;
import cn.cool.mapper.UserLikeArticleMapper;
import cn.cool.result.ResponseResult;
import cn.cool.service.ArticleService;
import cn.cool.utils.JWTUtils;
import cn.cool.utils.RedisUtil;
import cn.cool.vo.ArticleInfoVo;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.binarywang.java.emoji.EmojiConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author LiuH
 * @since 2021-01-23
 */
@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private EmojiConverter emojiConverter;
    @Autowired
    private RedisUtil redisUtil;

    /**
     * 添加 文章
     *
     * @param request
     * @param article
     * @return
     */
    @Override
    public Object addArticle(HttpServletRequest request, Article article) {
        //防止用户传" "
        if (article.getArtTitle() == null
                || article.getArtTitle().trim().length() == 0) {//判断标题是否为空 或 " "

            return ResponseResult.failure("请输入文章标题");

        } else if (article.getArtContent() == null
                || article.getArtContent().trim().length() == 0) {//判断内容是否为空 或 " "

            return ResponseResult.failure("请输入文章内容");

        }
        //根据token 获取作者id
        Integer authorId = JWTUtils.getUserId(request);
        article.setAuthorId(authorId);
        //设置创建时间
        article.setGmtCreate(new Date());
        //文章emoji表情转换
        String artContent = emojiConverter.toHtml(article.getArtContent());
        article.setArtContent(artContent);

        //插入数据库
        int result = articleMapper.insertSelective(article);

        if (result > 0) {
            return ResponseResult.success(200, "发表成功!");
        }

        return ResponseResult.failure("发表失败");
    }

    /**
     * 根据id查看文章
     *
     * @param artId
     * @return
     */
    @Override
    public Object getArticleInfo(HttpServletRequest request, Integer artId) {
        //获取文章信息
        ArticleInfoVo artInfo = articleMapper.getArtInfoAndAuthorInfo(artId);
        //存放文章点击量
        redisUtil.sSet("artHit:" + artId, JWTUtils.getUserId(request));
        //根据文章id获取点赞数量
        Integer likeCount = (Integer) redisUtil.hget("artLikeCount", "" + artId);
        //获取点击量
        long hits = redisUtil.sGetSetSize("artHit:" + artId);

        artInfo.setLikeCount(likeCount);
        artInfo.setArtHit(hits);

        if (artInfo != null) {
            return ResponseResult.success(200, "正在加载,请稍后", artInfo);
        }
        return ResponseResult.failure("加载失败!");
    }

}
